package br.com.q7solucoes.commons.utils;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Contem utilidades de String.
 *
 * @author Elenilson Vieira - elenilson[at]q7solucoes.com.br
 * @since 14 de fevereiro 2011
 * @version 1.0
 * @see www.q7solucoes.com.br
 */
public class StringUtils {

    public static final String HTML_TEMPLATE_PATH = "/br/com/q7solucoes/parsercinemaq7/files/template.htm";
    
    private StringUtils() {
    }

    /**
     * Converte a String para UTF-8
     *
     * @param value o String Unicode
     *
     * @return o String UTF-8
     */
    public static String removeAccents(String value) {




         value = value.replaceAll("&#8206;", "");



        value = value.replaceAll("Á", "A");
        value = value.replaceAll("É", "E");
        value = value.replaceAll("Í", "I");
        value = value.replaceAll("Ó", "O");
        value = value.replaceAll("Ú", "U");

        value = value.replaceAll("Â", "A");
        value = value.replaceAll("Ê", "E");
        value = value.replaceAll("Î", "I");
        value = value.replaceAll("Ô", "O");
        value = value.replaceAll("Û", "U");

        value = value.replaceAll("Ã", "A");
        value = value.replaceAll("Ẽ", "E");
        value = value.replaceAll("Ĩ", "I");
        value = value.replaceAll("Õ", "O");
        value = value.replaceAll("Ũ", "U");

        value = value.replaceAll("À", "A");
        value = value.replaceAll("È", "E");
        value = value.replaceAll("Ì", "I");
        value = value.replaceAll("Ò", "O");
        value = value.replaceAll("Ù", "U");

        value = value.replaceAll("á", "a");
        value = value.replaceAll("é", "e");
        value = value.replaceAll("í", "i");
        value = value.replaceAll("ó", "o");
        value = value.replaceAll("ú", "u");

        value = value.replaceAll("â", "a");
        value = value.replaceAll("ê", "e");
        value = value.replaceAll("î", "i");
        value = value.replaceAll("ô", "o");
        value = value.replaceAll("û", "u");

        value = value.replaceAll("ã", "a");
        value = value.replaceAll("ẽ", "e");
        value = value.replaceAll("ĩ", "i");
        value = value.replaceAll("õ", "o");
        value = value.replaceAll("ũ", "u");

        value = value.replaceAll("à", "a");
        value = value.replaceAll("è", "e");
        value = value.replaceAll("ì", "i");
        value = value.replaceAll("ò", "o");
        value = value.replaceAll("ù", "u");

        value = value.replaceAll("ç", "c");
        value = value.replaceAll("–", "-");
        value = value.replaceAll("’", "'");
        value = value.replaceAll("&amp;", "&");

        return value;
    }

    /**
     * Pega um titulo e retorna uma lista de possiveis nomes de bandas que ele
     * possa representar. Leva em consideracao bandas com dois nomes (Bichinha
     * Arrumada) e titulos com mais de uma banda (Samba da Elite e Forro Pegado).
     *
     * @param title o titulo do post
     *
     * @return uma lista com possiveis nomes
     */
    public static List<String> buildPossiblesBandNames(String title) {
        /*** Lista de conjuncoes utilizadas ***/
        final Set<String> conjuctions = new HashSet<String>();
        conjuctions.add("e");
        conjuctions.add("da");
        conjuctions.add("de");
        conjuctions.add("do");
        conjuctions.add("&");

        /*** Lista de pontuacoes utilizadas ***/
        final Set<String> ponctuations = new HashSet<String>();
        ponctuations.add(".");
        ponctuations.add(",");
        ponctuations.add(":");
        ponctuations.add(";");

        /*** Faz a separacao de alguns caracteres ***/
        for (String ponctuation : ponctuations) {
            title = title.replace(ponctuation, " " + ponctuation + " ");
        }

        List<String> result = new ArrayList<String>();

        /*** Adiciona o titulo ***/
        result.add(title);

        String tokens[] = title.trim().split(" ");

        for (int i= 0; i < tokens.length; i++) {
            /*** Se for pontuacao nao entra pra lista ***/
            if(ponctuations.contains(tokens[i]))
                continue;

            if(conjuctions.contains(tokens[i])){
                try{
                    String name = String.format("%s %s %s", tokens[i - 1], tokens[i], tokens[i + 1]);
                    result.add(name);
                }catch(Exception ex){}

                try{
                    String name = String.format("%s %s %s %s", tokens[i - 2], tokens[i - 1], tokens[i], tokens[i + 1]);
                    result.add(name);
                }catch(Exception ex){}

                try{
                    String name = String.format("%s %s %s %s", tokens[i - 1], tokens[i], tokens[i + 1], tokens[i + 2]);
                    result.add(name);
                }catch(Exception ex){}

                try{
                    String name = String.format("%s %s %s %s %s", tokens[i - 2], tokens[i - 1], tokens[i], tokens[i + 1], tokens[i + 2]);
                    result.add(name);
                }catch(Exception ex){}
                
            }else{
                result.add(tokens[i]);
                
                try{
                    String name = String.format("%s %s", tokens[i], tokens[i + 1]);
                    result.add(name);
                }catch(Exception ex){}

                try{
                    String name = String.format("%s %s %s", tokens[i], tokens[i + 1], tokens[i + 2]);
                    result.add(name);
                }catch(Exception ex){}

                try{
                    String name = String.format("%s %s %s %s", tokens[i], tokens[i + 1], tokens[i + 2], tokens[i + 3]);
                    result.add(name);
                }catch(Exception ex){}
            }
        }

        return result;
    }

    /**
     * Converte uma data para o formato dd/mm/aaaa
     *
     * @param date uma data
     *
     * @return uma String no formato dd/mm/aaaa
     */
    public static String converteDateToString(Date date){
        String day = intToString(date.getDate());
        String month = intToString(date.getMonth() + 1);
        
        return String.format("%s/%s/%s", day,
                month, date.getYear() + 1900);
    }
    
    /**
     * Passa o conteudo de um filme para HTML
     * 
     * @param title o titulo do filme
     * @param imageLink o link da imagem
     * @param censorship a censura
     * @param trailerLink o link do trailer
     * @param sinopsis a sinopse
     * @param sessions a lista de categorias no formato: Sala 3 (Todos os Dias): 16h20 – 20h40 (Legendado)
     * 
     * @return o html
     */
    public static String buildMovieContent(String title, String imageLink, String censorship, String trailerLink, 
            String sinopsis, List<String> sessions){
        
        String html = FileUtilsFromJar.readStringFromAFileJar(HTML_TEMPLATE_PATH);
        
        html = html.replaceAll("TITLE", title);
        html = html.replaceAll("IMAGE_LINK", imageLink);

        if(censorship != null)
            html = html.replaceAll("CENSORSHIP", censorship);
        else
            html = html.replaceAll("<div>Censura:  CENSORSHIP</div>", " ").trim();

        html = html.replaceAll("SINOPSIS", sinopsis);

        if(trailerLink != null)
            html = html.replaceAll("TRAILLER_LINK", trailerLink);
        else
            html = html.replaceAll("Veja o <a href=\"TRAILLER_LINK\">Trailer</a>", " ").trim();
        
        StringBuilder sessionsBuiler = new StringBuilder();
        for (String session : sessions) {
            sessionsBuiler.append("<div>").append(session).append("</div>").append("\n");
        }
        
        html = html.replaceAll("SESSIONS", sessionsBuiler.toString());
        
        return html;
    }

    /**
     * Converte uma String na codificacao ISO-8859-1 para a codificacao UTF-8
     *
     * @param stringIso a String ISO-8859-1
     *
     * @return a String convertida pra UTF-8
     */
    public static String convertIsoToUTF8(String stringIso) throws UnsupportedEncodingException{
        return new String(stringIso.getBytes("ISO-8859-1"), "UTF-8");  
    }

    /**
     * Converte uma String na codificacao UTF-8 para a codificacao ISO-8859-1
     *
     * @param stringUTF8 a String UTF-8
     *
     * @return a String convertida pra ISO-8859-1
     */
    public static String convertUTF8ToIso(String stringUTF8) throws UnsupportedEncodingException{
        return new String(stringUTF8.getBytes("UTF-8"), "ISO-8859-1");  
    }
    
    /**
     * Cria a data do cinema de sexta a quinta
     * 
     * @return sexta a quinta
     */
    public static String buildCineDate() {
        GregorianCalendar now = (GregorianCalendar) GregorianCalendar.getInstance();
        
        /*** Procura a ultima sexta ***/
        while(now.get(GregorianCalendar.DAY_OF_WEEK) != GregorianCalendar.FRIDAY){
            now.add(GregorianCalendar.DAY_OF_YEAR, -1);
        }
        
        String day = intToString(now.get(GregorianCalendar.DAY_OF_MONTH));
        String month = intToString(now.get(GregorianCalendar.MONTH) + 1);
        String firstDate = String.format("%s/%s/%d", day, month, now.get(GregorianCalendar.YEAR));
        
        /*** Procura a proxima quinta ***/
        while(now.get(GregorianCalendar.DAY_OF_WEEK) != GregorianCalendar.THURSDAY){
            now.add(GregorianCalendar.DAY_OF_YEAR, 1);
        }
        
        day = intToString(now.get(GregorianCalendar.DAY_OF_MONTH));
        month = intToString(now.get(GregorianCalendar.MONTH) + 1);
        String lastDate = String.format("%s/%s/%d", day, month, now.get(GregorianCalendar.YEAR));
        
        return String.format("%s a %s", firstDate, lastDate);
    }
    
    /**
     * Converte um inteiro para string mantendo o inicio com 0
     * 
     * @param i um inteiro
     * 
     * @return o inteiro em string com 0 no inicio de for menor que 10
     */
    public static String intToString(int i){
        return i < 10 ? String.format("0%d", i) : String.format("%d", i);
    }
    
    /**
     * Converte um conteudo para um formato
     * 
     * @param content o conteudo
     * @param encode o formato
     * 
     * @return o conteudo formatado
     */
    public static String convert(String content, String encode) {  
        Charset charset = Charset.forName(encode);  
        ByteBuffer bb = charset.encode(content);  
        
        return bb.toString();  
    }  
    
    /**
     * Converte um conteudo para UTF-8
     * 
     * @param s o conteudo
     * 
     * @return o conteudo formatado para UTF-8
     */
    public static String convertToUTF8(String s) throws UnsupportedEncodingException {  
        return new String(s.getBytes("UTF-8"), "UTF-8");  
    }  
 
}
